﻿CREATE PROCEDURE [config].[UpdateInstanceSettings](
	@ConfigXml xml, 
	@RefreshConfig bit = 0
)
AS
BEGIN
	IF(@RefreshConfig = 1) TRUNCATE TABLE [config].[InstanceSettings];

	DECLARE @OutputRecords table([Action] varchar(50), [Name] varchar(50));

	DECLARE @docHandle int
	EXEC sp_xml_preparedocument @docHandle OUTPUT, @ConfigXml;

	MERGE [config].[InstanceSettings] AS target
	USING(
		SELECT *
		FROM OPENXML(@docHandle,'Config/Item')
		WITH(
			[Name] varchar(50) '@name',
			[Value] varchar(4000) '@value',
			[Overwrite] bit '@overwrite'
		)
	) AS source
		ON (source.[Name] = target.[Name])
	WHEN MATCHED THEN
		UPDATE SET
			[Value] = (CASE source.[Overwrite] WHEN 1 THEN source.[Value] ELSE target.[Value] END)
	WHEN NOT MATCHED BY TARGET THEN
		INSERT([Name],[Value])
		VALUES(source.[Name],source.[Value])
	WHEN NOT MATCHED BY SOURCE THEN
		DELETE
	OUTPUT $action, deleted.[Name] INTO @OutputRecords;
	
	DELETE [config].[InstanceSettings]
	FROM [config].[InstanceSettings] AS tbl
	INNER JOIN @OutputRecords AS opr
		ON (opr.[Name] = tbl.[Name])
		AND(opr.[Action] = 'DELETED')
		
	RETURN(0);
END